<template>
  <view class="current-order page-box">
    <u-navbar
      title="服务中订单"
      @leftClick="$jump('/pages/user/user', { method: 'reLaunch' })"
      :placeholder="true"
    >
    </u-navbar>
    <view v-if="currentTechnicianId">
      <u-cell-group :border="false">
        <u-cell title="已出发">
          <template slot="value">
            <u-switch v-model="serverIsGo" :disabled="disabled"></u-switch>
          </template>
        </u-cell>
        <u-cell title="服务类型" :value="projectData.title"></u-cell>
        <u-cell title="客户名称" :value="clientInfo.realName"></u-cell>
        <u-cell title="客户联系方式" :value="clientInfo.mobilePhone"></u-cell>
        <u-cell
          title="客户地址"
          :value="normalAddress.address + normalAddress.addressDetail"
        ></u-cell>
        <u-cell
          v-if="orderData"
          title="客户预约时间"
          :value="$u.timeFormat(orderData.creatorTime, 'yyyy年mm月dd日 hh:MM')"
        >
        </u-cell>
        <u-cell title="客户下单金额">
          <template slot="value">
            <text style="color: #f60000" v-if="orderData">
              ¥ {{ Number(projectData.price) + orderData.distance * 10 }}
            </text>
          </template>
        </u-cell>
        <u-cell
          title="服务时长"
          :value="projectData.project_time + '分钟'"
        ></u-cell>
      </u-cell-group>

      <view class="show_time" v-if="orderData.status_code !== 4">
        <view>客户已下单时间</view>
        <!--   :time="projectData.project_time * 60 * 1000" -->
        <view>
          <u-count-down
            ref="orderCountDown"
            :time="countDownTime"
            format="SSS"
            :autoStart="orderData.status_code == 3"
            @finish="timeOrderFinish"
            millisecond
            @change="onChangeTime"
          >
            <view class="time">
              <text class="time__item"
                >{{
                  timeData.hours >= 10 ? timeData.hours : "0" + timeData.hours
                }}&nbsp;:</text
              >
              <text class="time__item"
                >{{
                  timeData.minutes >= 10
                    ? timeData.minutes
                    : "0" + timeData.minutes
                }}&nbsp;:</text
              >
              <text class="time__item"
                >{{
                  timeData.seconds >= 10
                    ? timeData.seconds
                    : "0" + timeData.seconds
                }}&nbsp;</text
              >
            </view>
          </u-count-down>
        </view>

        <view
          style="margin-top: 100rpx"
          class="flex justify-between items-center show_time_btn"
          @click="handleOrderBtn"
        >
          <!-- <view
            class="cancel-btn"
            v-if="orderData.status_code == 3"
            :data-order="0"
            >暂停</view
          > -->
          <view class="sure-btn" v-if="!orderData.start_time" :data-order="1"
            >开始</view
          >
        </view>
      </view>
      <view class="show_time" v-else>
        <view class="time">
          <text class="time__item"> 已完成服务 </text>
        </view>
      </view>
    </view>

    <u-empty
      v-else
      mode="data"
      icon="http://cdn.uviewui.com/uview/empty/data.png"
    >
    </u-empty>
  </view>
</template>
<script>
import { getModelInfo, getModelList, updateModel } from "@/api";
import { getSearchFilter } from "@/common/function";
import infoMixin from "@/common/mixins/info";
export default {
  mixins: [infoMixin],
  data() {
    return {
      title: "账单详情",
      disabled: true, //禁止点击开关
      serverIsGo: false, //判断技师是否触发
      projectData: {}, //项目信息
      clientInfo: {}, //用户真实信息
      technicianItemData: {}, //技师列表信息
      normalAddress: {}, //用户默认地址信息
      orderData: {}, //订单详情信息
      clientInfo: {}, //客户信息
      currentTechnicianId: "", //当前技师基础信息id
      technicianItemId: "", //技师列表信息_id
      normalAddress: {}, //默认地址信息
      projectData: {}, //项目信息
      loading: false, // 开始按钮防重复点击
      timeData: {}, //倒计时时间
      countDownTime: 0, //计时时间
    };
  },
  components: {},
  watch: {},
  methods: {
    // 获取详情数据
    async getOrderDetail(baseInfo_id) {
      let that = this;
      let result = {};
      let filter = {
        currentPage: 1,
        pageSize: -1,
        connect: "and",
        filter: [getSearchFilter({ baseInfo_id }, { method: "eq" })].flat(2),
        sort: {
          go_time: "desc",
        },
      };
      return await getModelList("66002f4f5efd5153ff566ec3", filter)
        .then(async (res) => {
          result = res?.data?.list?.[0];
          this.serverIsGo = result.is_orders == 1 ? true : false;
          await Promise.all([
            that.getUserInfo(result.user_id),
            that.getProjectInfo(result.current_project_Info),
            that.getNormalAddress(result.address_id),
          ]);
          return result;
        })
        .catch((err) => {
          uni.showToast({
            title: err,
            icon: "none",
          });
        });
    },
    // 获取客户信息
    async getUserInfo(user_id) {
      let filterData = {
        currentPage: 1,
        pageSize: -1,
        filter: getSearchFilter({ user_id }, { method: "eq" }),
      };
      try {
        const { data, code } = await getModelList(
          "660247fe5efd5153ff56b807",
          filterData
        );
        if (code === 200) this.clientInfo = data?.list?.[0];
      } catch (error) {
        uni.showToast({
          title: error,
          icon: "none",
        });
      }
    },
    // 获取项目信息
    async getProjectInfo(id) {
      try {
        const { data, code } = await getModelInfo(
          "65b1d17c0921260197c48a76",
          id
        );
        if (code === 200) {
          this.projectData = data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取默认地址信息
    async getNormalAddress(creatorUserId) {
      const { data } = await getModelInfo(
        "65c1d9085efd5153ff55e6f4",
        creatorUserId
      );
      this.normalAddress = data;
    },
    //获取当前技师的技师列表
    async getCurrentTechnicianData(technician_Info) {
      let filter = {
        currentPage: 1,
        pageSize: -1,
        filter: getSearchFilter({ technician_Info }, { method: "eq" }),
      };
      // 获取当前技师的技师列表
      const { data } = await getModelList("65fbe6475efd5153ff566a8b", filter);
      // console.log(data);
      this.technicianItemData = data?.list?.[0];
    },
    // 倒计时时间循环
    onChangeTime(e) {
      // 开始触发节流
      this.timeData = e;
    },
    //开始计时静态方法
    start() {
      this.$refs.orderCountDown.start();
    },
    // 修改订单为已完成 停止计时 重新发送请求获取订单数据
    async timeOrderFinish() {
      if (!this.orderData.start_time) return;
      let that = this;
      this.changeOrderStatus(4).then(async () => {
        let [orderData] = await Promise.all([
          this.getOrderDetail(that.orderData.baseInfo_id),
          this.updateModelStatus(1),
        ]);

        this.orderData = orderData;
      });

      uni.showToast({
        title: "订单已结束",
        icon: "none",
      });
      this.loading = true;
    },
    // 修改技师状态为服务中
    async updateModelStatus(technician_status) {
      // 技师状态变为服务中
      return await updateModel(
        "65fbe6475efd5153ff566a8b",
        { technician_status },
        this.technicianItemData._id
      );
    },
    // 将订单状态改为服务中
    async changeOrderStatus(status_code) {
      return await updateModel(
        "66002f4f5efd5153ff566ec3",
        {
          status_code,
          start_time: Date.now(),
        },
        this.orderData._id
      );
    },
    // 点击开始按钮 开始计时,修改订单状态为服务中
    async handleOrderBtn(e) {
      if (this.loading) return;
      if (e.target.dataset.order) {
        // 改变订单状态
        await this.changeOrderStatus(3).then(async () => {
          //跟新订单状态code
          let res = await this.getOrderDetail(this.currentTechnicianId);
          this.orderData = res;
          // 开市
          this.start();
          this.loading = true;
        });
      }
    },
  },
  onReady() {},
  async onShow() {
    if (this.currentTechnicianId) {
      try {
        let [res] = await Promise.all([
          this.getOrderDetail(this.currentTechnicianId),
          this.getCurrentTechnicianData(this.currentTechnicianId),
        ]);
        this.orderData = res;
        //判断有开始时间时 开始计时
        if (this.orderData.start_time) {
          this.countDownTime =
            this.projectData?.project_time * 60 * 1000 -
            (Date.now() - this.orderData.start_time);
          // 10 * 1000 - (Date.now() - this.orderData.start_time);
          this.$refs.orderCountDown.start();
        } else {
          this.countDownTime = this.projectData?.project_time * 60 * 1000;
          // this.countDownTime = 10 * 1000;
        }
      } catch (error) {
        console.log(error);
      }
    }
  },
  async onLoad(options) {
    let { technicianId } = options;
    this.currentTechnicianId = technicianId;
  },
};
</script>

<style lang="scss" scoped>
%button-base {
  min-width: 300rpx;
  height: 88rpx;
  padding: 10rpx;
  font-size: 38rpx;
  border-radius: 55rpx;
  text-align: center;
  line-height: 88rpx;
  margin-left: 20rpx;
}

.current-order {
  .show_time {
    width: 100%;
    display: grid;
    place-content: center;
    text-align: center;
    margin-top: 100rpx;

    .time {
      // width: 500rpx;
      margin-top: 30rpx;
      @include flex;
      align-items: center;
      justify-content: center;

      &__item {
        color: $u-theme-color;
        font-size: 60rpx;
        text-align: center;
      }
    }

    &_btn {
      @include flex;
      align-items: center;
      justify-content: space-around;
      margin-top: 20px;

      .cancel-btn {
        @extend %button-base;
        background-color: #f6ebe7;
        color: $u-theme-color;
      }

      .sure-btn {
        @extend %button-base;
        color: #fff;
        background: $u-theme-color;
      }
    }
  }
}
</style>
d
